import * as path from "path";
import * as https from "https";
import * as http from "http";
import express from 'express';
import { getLogger, configure } from 'log4js';
import { lConfig } from '../config/config';
import * as fs from "fs";

configure('./log4js.json');
const logger = getLogger('Server');
let httpsServer: http.Server;

const certFile = path.resolve(process.cwd(), './certs/server.crt');
const keyFile = path.resolve(process.cwd(), './certs/server.key');
[certFile, keyFile].forEach(file => {
  if (!fs.existsSync(file)) {
    logger.error('Can not find $s!', file);
    process.exit(-1);
  }
});

const tls = {
  cert: fs.readFileSync(certFile),
  key: fs.readFileSync(keyFile),
};

export default async function runHttpsServer(app) {
  console.log('-----------------', path.resolve(lConfig.publicDirectory))


  app.use('/', express.static(path.resolve(lConfig.publicDirectory), { maxAge: '30d' }));

  /*app.get('*', (req, res, next) => {
    res.status(404).send({ res: '404' });
  });*/


  app.post('/test-data', function (req, res, next) {
    // console.log('-----------------', req.body)
    // res.status(200).send({ res: 'xxxxxxxx' });
  });

  httpsServer = https.createServer(tls, app);
  httpsServer.listen(lConfig.listeningPort);
  const httpServer = http.createServer(app);
  httpServer.listen(lConfig.listeningRedirectPort);

  return httpsServer
}
